<template>
  <basic-container page-title="DNS配置" custom-content>
    <template #filter>
      <div class="filter flex justify-between items-center">
        <div class="filter-left flex items-center gap-x-4">
          <el-button type="primary" @click="openEditDnsServerDialog()">
            添加
          </el-button>
          <el-input
            v-model="searchKeyword"
            :placeholder="placeholder"
            class="w-[360px] search-input"
            clearable
          >
            <template #prepend>
              <el-select
                v-model="activeSearchType"
                placeholder="请选择"
                class="w-[115px]"
              >
                <el-option
                  v-for="item in searchTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </template>
            <template #append>
              <el-button :icon="Search" @click="handleSearch" />
            </template>
          </el-input>
          <basic-refresh-btn :loading="loading" @click="getList()" />
        </div>
      </div>
    </template>

    <el-table
      v-loading="loading"
      :data="tableData"
      class="basic-table"
      :tooltip-options="{ popperClass: 'basic-tooltip' }"
      height="100%"
      @sort-change="handleSortChange"
    >
      <template #empty><TableEmpty /></template>
      <el-table-column
        type="index"
        label="序号"
        width="80"
        fixed="left"
      ></el-table-column>
      <!-- <el-table-column
        label="DNS服务器域名"
        show-overflow-tooltip
        min-width="200"
      >
        <template #default="{ row }">
          <span v-format-table-cell="row.domain"></span>
        </template>
      </el-table-column> -->
      <el-table-column
        label="DNS服务器地址"
        show-overflow-tooltip
        min-width="200"
      >
        <template #default="{ row }">
          <span v-format-table-cell="row.addr"></span>
        </template>
      </el-table-column>
      <!--
      <el-table-column label="IP地址" min-width="150">
        <template #default="{ row }">
          <span v-format-table-cell="row.ip"></span>
        </template>
      </el-table-column>
      -->
      <el-table-column label="解析域名数" min-width="150">
        <template #default="{ row }">
          <span v-format-table-cell="row.domain_num"></span>
        </template>
      </el-table-column>
      <el-table-column label="自动分配" min-width="150">
        <template #default="{ row }">
          <basic-switch
            need-loading
            :model-value="row.assign_status"
            :loading-change="() => handleEditStatus(row)"
          ></basic-switch>
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="created_at"
        sortable="custom"
        label="添加时间"
        min-width="180"
      >
        <template #default="{ row }">
          <span v-format-unix="row.created_at"></span>
        </template>
      </el-table-column> -->
      <el-table-column label="备注" min-width="220">
        <template #default="{ row }">
          <basic-edit-table-remark
            :content="row.remark"
            :submit="value => handleEditRemark(row, value)"
          ></basic-edit-table-remark>
        </template>
      </el-table-column>
      <el-table-column
        prop="updated_at"
        sortable="custom"
        label="更新时间"
        min-width="180"
      >
        <template #default="{ row }">
          <span v-format-unix="row.updated_at"></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="110" fixed="right">
        <template #default="{ row }">
          <div class="flex gap-x-4">
            <el-link
              type="primary"
              :underline="false"
              @click="openEditDnsServerDialog(row)"
            >
              编辑
            </el-link>
            <el-link
              type="danger"
              :disabled="+row.domain_num != 0 || +row.user_num != 0"
              :underline="false"
              @click="handleDelete(row)"
            >
              删除
            </el-link>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <basic-pagination
        :pagination="pagination"
        @change="getList()"
      ></basic-pagination>
    </template>
  </basic-container>

  <edit-dns-server-dialog
    v-model:visible="editDns.visible"
    v-model:loading="editDns.loading"
    :record="editDns.record"
    @reload="getList()"
  ></edit-dns-server-dialog>
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'

import type { CommonParams } from '@/apis/model/_utils'
import type { DnsServerModel } from '@/apis/model/dns'
import { BasicContainer } from '@/components/application'
import { useListRequest } from '@/hooks/useListRequest'
import ToastUtils from '@/utils/toast'

import EditDnsServerDialog from './dialogs/EditDnsServerDialog.vue'

type IQuery = Omit<
  CommonParams<'/v1/ns', 'get'>,
  'offset' | 'limit' | 'sort' | 'order'
>

/**
 * 查询参数
 */
const queryParams = reactive<IQuery & SortCustomParams>({
  addr: '',
  remark: '',
  sort: null,
  order: null
})

/**
 * 多类型搜索
 */
const searchTypeOptions = [
  { label: '服务器地址', value: 'addr' },
  { label: '备注', value: 'remark' }
]

const { activeSearchType, searchKeyword, placeholder } = useMultipartSearch(
  searchTypeOptions,
  queryParams
)

/**
 * 获取列表数据
 */
const {
  data: tableData,
  getList,
  pagination,
  loading
} = useListRequest(dnsServerListApi, queryParams)
onMounted(getList)

// const {
//   loading: domainLoading,
//   remoteMethod: domainRemoteMethod,
//   opts: domainOpts
// } = useSelectRemote(domainListApi, {
//   valueKey: 'name',
//   labelKey: 'name',
//   queryKey: 'name'
// })
// domainRemoteMethod('')
/**
 * 搜索
 */
const handleSearch = () => {
  pagination.page = 1
  pagination.offset = 0
  getList()
}

/**
 * 添加/编辑dns服务器
 */
const editDns = reactive<CommonDialog>({
  visible: false,
  record: null,
  loading: false
})
const openEditDnsServerDialog = (row?: DnsServerModel) => {
  editDns.record = row
  editDns.visible = true
}

const { setMessageBox } = useMessageBox()

/**
 * 删除
 */
const handleDelete = (row: DnsServerModel) => {
  setMessageBox({
    content:
      '确认删除此地址？删除地址，对应的解析记录可能仍旧生效。想要地址失效，需要到域名注册商处删除对应地址。',
    title: '删除DNS服务器地址提示',
    async submit() {
      try {
        await deleteDnsServerApi({ id: row.id! })
        decPageByData(pagination, tableData)
        getList()
        ToastUtils.success('删除成功')

        setMessageBox({ visible: false })
      } finally {
        setMessageBox({ loading: false })
      }
    }
  })
}

/**
 * 修改分配状态
 */
const handleEditStatus = async (row: DnsServerModel) => {
  await putDnsServerApi({
    assign_status: row.assign_status === 1 ? 2 : 1,
    id: row.id!
  })
  getList()
  ToastUtils.success('修改成功')
}

// const desRef = ref()
// const { fetchFn: desFetch } = useSearch('remark', dnsServerListApi, {
//   domRef: desRef
// })
/**
 * 修改备注
 */
const handleEditRemark = async (row: DnsServerModel, remark: string) => {
  await putDnsServerApi({ id: row.id!, remark })
  getList()
  ToastUtils.success('修改成功')
}

function handleSortChange(params) {
  const { sort, order } = getSortValue(params)
  queryParams.order = order
  queryParams.sort = sort
  pagination.page = 1
  getList()
}
</script>

<style scoped lang="scss"></style>
